package cz.zcu.fav.rat.managed.bean;

import java.util.Set;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

import cz.zcu.fav.rat.beans.User;
import cz.zcu.fav.rat.beans.Object;
import cz.zcu.fav.rat.dataaccess.service.ObjectService;
import cz.zcu.fav.rat.dataaccess.service.UserService;
import cz.zcu.fav.rat.security.beans.UserSessionController;

@ManagedBean(name = "favouriteBean")
@RequestScoped
public class FavouriteBean
{
	private transient UserService userService;
	private transient ObjectService objectService;

	@ManagedProperty(value = "#{param.id}")
	private Integer id;
	private User user;

	public UserService getUserService()
	{
		if (userService == null)
		{
			userService = SpringBeanFactory.getInstance().getBean(
					"userService", UserService.class);
		}
		return userService;
	}

	public ObjectService getObjectService()
	{
		if (objectService == null)
		{
			objectService = SpringBeanFactory.getInstance().getBean(
					"objectService", ObjectService.class);
		}
		return objectService;
	}

	@PostConstruct
	public void init()
	{
		String idAsString = FacesContext.getCurrentInstance()
				.getExternalContext().getRequestParameterMap().get("id");
		try
		{
			id = Integer.valueOf(idAsString);
		} catch (NumberFormatException ex)
		{
			id = null;
		}
		
		
		user = getUserService().get(
				UserSessionController.getLoggedUserBean().getId());
	}

	public boolean isFavourite()
	{
		Set<Object> favourites = user.getFavourites();
		for (Object obj : favourites)
		{
			if (obj.getId().equals(id))
			{
				return true;
			}

		}
		return false;
	}

	public void unfavourite()
	{
		getUserService()
				.removeFavouriteToUser(user, getObjectService().get(id));
	}

	public void favourite()
	{
		getUserService()
				.addNewFavouriteToUser(user, getObjectService().get(id));
	}

	public Integer getId()
	{
		return id;
	}

	public void setId(Integer id)
	{
		this.id = id;
	}
}
